<?php

namespace app\data\controller\record;

use app\data\service\ExpressService;
use think\admin\Controller;

/**
 * 调度员配置
 * Class CityDockingConfig
 * @package app\data\controller\record
 */
class CityDockingConfig extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'data_city_docking_config';

    /**
     * 调度员管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '调度员管理';
        $query = $this->_query($this->table);
        $query->equal('status')->dateBetween('create_at');

        if (!empty($name = $this->request->request('uuid_docking_name', ''))) {
            $uuids = $this->app->db->name('work_user')->where('name', 'like', "%{$name}%")->field('id,name')->select()->toArray();
            $query->whereIn('uuid_docking', array_column($uuids, 'id'));
        }

        $query->where(['deleted' => 0])->order('id desc')->page();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        ExpressService::instance()->formatCity($data);
        $uuidsDocking = array_column($data, 'uuid_docking');
        $workUsers = $this->app->db->name('work_user')->whereIn('id', $uuidsDocking)->select()->toArray();
        foreach ($workUsers as $workUser) {
            $userId2Name[$workUser['id']] = $workUser['name'];
        }

        foreach ($data as &$item) {
            $item['name_docking'] = $userId2Name[$item['uuid_docking']] ?? '';
        }
    }

    /**
     * 调度员配置
     * @throws \think\db\exception\DbException
     */
    public function region()
    {
        if ($this->request->isGet()) {
            $this->title = '配送区域管理';
            $this->citys = ExpressService::instance()->region(3, null);
            $this->fetch('form_region');
        } else {
            $data = $this->_vali(['nos.default' => '', 'oks.default' => '']);
            if ($data['nos']) $this->app->db->name('BasePostageRegion')->whereIn('id', str2arr($data['nos']))->update(['status' => 0]);
            if ($data['oks']) $this->app->db->name('BasePostageRegion')->whereIn('id', str2arr($data['oks']))->update(['status' => 1]);
            $this->success('修改配送区域成功！', 'javascript:history.back()');
        }
    }

    /**
     * 添加调度员
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->title = '添加调度员';
        $this->_form($this->table, 'form', 'id');
    }

    /**
     * 编辑调度员
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->title = '编辑调度员';
        $this->_form($this->table, 'form', 'id');
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%2%")->order('id desc')->select()->toArray();
            $this->citys = ExpressService::instance()->region(2, 1);

        } else {
            if (empty($data['uuid_docking'])) {
                $this->error('调度员不能为空');
            }

            if ($data['content'] == '[]') {
                $this->error('配置地区不能为空');
            }

            $message = ExpressService::instance()->checkCanUpdate($data['id'] ?? 0, $data);

            if (!empty($message)) {
                $this->error($message);
            }
        }
    }

    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result(bool $result, $data)
    {
        if ($result && $this->request->isPost()) {

            if (empty($data['id'])) {
                $data['id'] = $this->app->db->name($this->table)->order('id', 'desc')->limit(1)->value('id');
            }

            // 保存配置
            $wheres = ExpressService::instance()->formatWhere($data);
            ExpressService::instance()->updateBasePostageRegionConfig($data['id'], $wheres ?? [], $data['uuid_docking']);

            $this->success('保存成功！', 'javascript:history.back()');
        }
    }

    /**
     * 启用或禁用调度配置
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]), 'id');
    }

    /**
     * 删除调度配置
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $data = $this->_vali([
            'id.require' => 'id不能为空！',
        ]);

        $this->app->db->name('base_postage_region')->where('city_docking_config_id', $data['id'])->update(['city_docking_config_id' => 0, 'uuid_docking' => 0]);

        $this->_delete($this->table, 'id');
    }

    /**
     * 默认调度员配置
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config()
    {
        $this->skey = 'DefaultDockingUuid';
        $this->title = '默认调度员配置';
        $this->_sysdata();
    }

    /**
     * 配置数据处理
     * @param string $tpl 模板文件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _sysdata(string $tpl = '')
    {
        if ($this->request->isGet()) {
            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%2%")->order('id desc')->select()->toArray();
            $this->data = sysdata($this->skey);
            $this->fetch($tpl);
        } else {

            $data = $this->request->post();
            if (empty($data['uuid'])) {
                $this->error('调度员不能为空');
            }

            sysdata($this->skey, $data['uuid']);

            $this->success('配置修改成功');
        }
    }

}